﻿using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core.DynamicForm;
using System.ComponentModel;
using System.Collections.Generic;
using System;
using Kingdee.BOS.ServiceHelper;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    [HotUpdate]
    [Description("同步更新采购流水号")]
    public class PurchaseOrderSave : AbstractOperationServicePlugIn
    {
        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            //构建采购流水号元数据
            IMetaDataService metaService = ServiceFactory.GetService<IMetaDataService>(Context);
            FormMetadata purchaseSnMeta = (FormMetadata)metaService.Load(Context, "PMAF_PurchaseSn");
            List<DynamicObject> list = new List<DynamicObject>();
            //读取单据数据，为采购流水号数据赋值
            foreach (DynamicObject entity in e.DataEntitys)
            {
                if (entity != null)
                {
                    string formId = entity["FFormId"].ToString();       //单据类型
                    int billId = Convert.ToInt32(entity["Id"]);         //单据Id
                    var purOrderNo = entity["BillNo"];                  //订单号
                    var supplier = (DynamicObject)entity["SupplierId"]; //供应商
                    var supplierId = supplier["Id"];                    //供应商Id
                    var emp = (DynamicObject)entity["PurchaserId"];     //业务员
                    var empId = emp["Id"];                              //业务员Id
                    var createDate = entity["Date"];                    //创建日期
                    var purOrg = (DynamicObject)entity["PurchaseOrgId"];
                    var purOrgId = purOrg["Id"];
                    var rebate = entity["F_PMAF_Rebate"];
                    if (string.Equals(formId, "PUR_PurchaseOrder"))
                    {
                        //设置采购订单过滤条件并查询订单
                        OQLFilter purOrderFilter = new OQLFilter
                        {
                            new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", billId) }
                        };
                        DynamicObject[] purOrders = BusinessDataServiceHelper.Load(Context, "PUR_PurchaseOrder", null, purOrderFilter);
                        DynamicObjectCollection entry = (DynamicObjectCollection)entity["POOrderEntry"];
                        //在原订单修改过程中保留行的信息
                        DynamicObjectCollection oldFlagEntries = new DynamicObjectCollection();
                        //原订单有数据
                        if (purOrders.Length > 0)
                        {
                            DynamicObjectCollection oldEntries = (DynamicObjectCollection)purOrders[0]["POOrderEntry"];
                            //原订单明细行ID
                            int[] oldEntryIds = new int[oldEntries.Count];
                            int i = 0;
                            foreach (DynamicObject oldEntry in oldEntries)
                            {
                                oldEntryIds[i] = Convert.ToInt32(oldEntry["Id"]);
                                i++;
                            }
                            foreach (DynamicObject row in entry)
                            {
                                DynamicObject oPurchaseSnMeta = new DynamicObject(purchaseSnMeta.BusinessInfo.GetDynamicObjectType());
                                int currentEntryId = Convert.ToInt32(row["Id"]);    //行Id
                                var material = (DynamicObject)row["MaterialId"];    //物料
                                var materialId = Convert.ToInt32(material["Id"]);   //物料Id
                                var purQty = Convert.ToDecimal(row["Qty"]);         //采购数量
                                var purchaseSn = row["F_PMAF_PurchaseSN"];          //流水号
                                var purchaseSnId = row["F_PMAF_PurchaseSNId"];          //流水号Id
                                var contractMonth = (DynamicObject)row["F_PMAF_ContractMonth"];    //合约月
                                string contractMonthId = string.Empty;
                                if(contractMonth != null)
                                {
                                    contractMonthId = contractMonth["Id"].ToString();
                                }
                                decimal purPrice = Convert.ToDecimal(row["TaxPrice"]);
                                int contractType = Convert.ToInt32(row["F_PMAF_ContractType"]);
                                decimal oldQty = 0;                                 //原采购数量
                                decimal changeQty = 0;                              //变化数量
                                int oldPurchaseId = 0;                              //原采购流水号
                                int oldMaterialId = 0;                              //原物料Id
                                bool entryIdExists = Array.Exists(oldEntryIds, element => element == currentEntryId);
                                foreach (DynamicObject oldEntry in oldEntries)
                                {
                                    int oldEntryId = Convert.ToInt32(oldEntry["Id"]);
                                    DynamicObject oldMaterial = (DynamicObject)oldEntry["MaterialId"];
                                    oldMaterialId = Convert.ToInt32(oldMaterial["Id"]);
                                    //如果有保留行，放入保留行的集合
                                    if (currentEntryId == oldEntryId && materialId == oldMaterialId)
                                    {
                                        oldFlagEntries.Add(oldEntry);
                                        if (purchaseSnId == null)
                                        {
                                            oPurchaseSnMeta["Number"] = purchaseSn;
                                            oPurchaseSnMeta["F_PMAF_POOderNo"] = purOrderNo;
                                            oPurchaseSnMeta["F_PMAF_SupplierID_Id"] = supplierId;
                                            oPurchaseSnMeta["F_PMAF_SupplierID"] = supplier;
                                            oPurchaseSnMeta["F_PMAF_EmpID_Id"] = empId;
                                            oPurchaseSnMeta["F_PMAF_EmpID"] = emp;
                                            oPurchaseSnMeta["F_PMAF_MaterialID_Id"] = materialId;
                                            oPurchaseSnMeta["F_PMAF_MaterialID"] = material;
                                            oPurchaseSnMeta["F_PMAF_CreateDate_tzk"] = createDate;
                                            oPurchaseSnMeta["F_PMAF_ModifyDate_ca9"] = createDate;
                                            oPurchaseSnMeta["DocumentStatus"] = "C";            //单据状态
                                            oPurchaseSnMeta["ForbidStatus"] = "A";              //作废状态
                                            oPurchaseSnMeta["F_PMAF_PurchaseStatus"] = "A";
                                            oPurchaseSnMeta["F_PMAF_PurQty"] = purQty;          //采购数量
                                            oPurchaseSnMeta["F_PMAF_CurrentQty"] = purQty;      //当前数量
                                            oPurchaseSnMeta["F_PMAF_ContractMonth"] = contractMonth;
                                            oPurchaseSnMeta["F_PMAF_ContractMonth_Id"] = contractMonthId;
                                            oPurchaseSnMeta["F_PMAF_ContractType"] = contractType;
                                            oPurchaseSnMeta["F_PMAF_PurPrice"] = purPrice;
                                            oPurchaseSnMeta["F_PMAF_PurOrg"] = purOrg;
                                            oPurchaseSnMeta["F_PMAF_PurOrg_Id"] = purOrgId;
                                            oPurchaseSnMeta["F_PMAF_Rebate"] = rebate;
                                            list.Add(oPurchaseSnMeta);
                                        }
                                        else
                                        {
                                            oldQty = Convert.ToDecimal(oldEntry["Qty"]);
                                            changeQty = purQty - oldQty;
                                            oldPurchaseId = Convert.ToInt32(oldEntry["F_PMAF_PurchaseSnId_Id"]);
                                            DynamicObject[] purchaseSns = GetPurchaseSn(oldPurchaseId);
                                            if (purchaseSns != null && purchaseSns.Length > 0)
                                            {
                                                purchaseSns[0]["F_PMAF_PurQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_PurQty"]) + changeQty;
                                                purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]) + changeQty;
                                                purchaseSns[0]["F_PMAF_PurPrice"] = purPrice;
                                                BusinessDataServiceHelper.Save(Context, purchaseSns);
                                            }
                                        }
                                    }
                                    else if(currentEntryId == oldEntryId && materialId != oldMaterialId)
                                    {
                                        oldFlagEntries.Add(oldEntry);
                                        oldQty = Convert.ToDecimal(oldEntry["Qty"]);
                                        oldPurchaseId = Convert.ToInt32(oldEntry["F_PMAF_PurchaseSnId_Id"]);
                                        DynamicObject[] oldPurchaseSns = GetPurchaseSn(oldPurchaseId);
                                        if (oldPurchaseSns != null && oldPurchaseSns.Length > 0)
                                        {
                                            oldPurchaseSns[0]["F_PMAF_PurQty"] = Convert.ToDecimal(oldPurchaseSns[0]["F_PMAF_PurQty"]) - oldQty;
                                            oldPurchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(oldPurchaseSns[0]["F_PMAF_CurrentQty"]) - oldQty;
                                            BusinessDataServiceHelper.Save(Context, oldPurchaseSns);
                                        }
                                        oPurchaseSnMeta["Number"] = purchaseSn;
                                        oPurchaseSnMeta["F_PMAF_POOderNo"] = purOrderNo;
                                        oPurchaseSnMeta["F_PMAF_SupplierID_Id"] = supplierId;
                                        oPurchaseSnMeta["F_PMAF_SupplierID"] = supplier;
                                        oPurchaseSnMeta["F_PMAF_EmpID_Id"] = empId;
                                        oPurchaseSnMeta["F_PMAF_EmpID"] = emp;
                                        oPurchaseSnMeta["F_PMAF_MaterialID_Id"] = materialId;
                                        oPurchaseSnMeta["F_PMAF_MaterialID"] = material;
                                        oPurchaseSnMeta["F_PMAF_CreateDate_tzk"] = createDate;
                                        oPurchaseSnMeta["F_PMAF_ModifyDate_ca9"] = createDate;
                                        oPurchaseSnMeta["DocumentStatus"] = "C";            //单据状态
                                        oPurchaseSnMeta["ForbidStatus"] = "A";              //作废状态
                                        oPurchaseSnMeta["F_PMAF_PurchaseStatus"] = "A";
                                        oPurchaseSnMeta["F_PMAF_PurQty"] = purQty;          //采购数量
                                        oPurchaseSnMeta["F_PMAF_CurrentQty"] = purQty;      //当前数量
                                        oPurchaseSnMeta["F_PMAF_ContractMonth"] = contractMonth;
                                        oPurchaseSnMeta["F_PMAF_ContractMonth_Id"] = contractMonthId;
                                        oPurchaseSnMeta["F_PMAF_ContractType"] = contractType;
                                        oPurchaseSnMeta["F_PMAF_PurPrice"] = purPrice;
                                        oPurchaseSnMeta["F_PMAF_PurOrg"] = purOrg;
                                        oPurchaseSnMeta["F_PMAF_PurOrg_Id"] = purOrgId;
                                        oPurchaseSnMeta["F_PMAF_Rebate"] = rebate;
                                        list.Add(oPurchaseSnMeta);
                                    }
                                }
                                if (!entryIdExists)
                                {
                                    oPurchaseSnMeta["Number"] = purchaseSn;
                                    oPurchaseSnMeta["F_PMAF_POOderNo"] = purOrderNo;
                                    oPurchaseSnMeta["F_PMAF_SupplierID_Id"] = supplierId;
                                    oPurchaseSnMeta["F_PMAF_SupplierID"] = supplier;
                                    oPurchaseSnMeta["F_PMAF_EmpID_Id"] = empId;
                                    oPurchaseSnMeta["F_PMAF_EmpID"] = emp;
                                    oPurchaseSnMeta["F_PMAF_MaterialID_Id"] = materialId;
                                    oPurchaseSnMeta["F_PMAF_MaterialID"] = material;
                                    oPurchaseSnMeta["F_PMAF_CreateDate_tzk"] = createDate;
                                    oPurchaseSnMeta["F_PMAF_ModifyDate_ca9"] = createDate;
                                    oPurchaseSnMeta["DocumentStatus"] = "C";            //单据状态
                                    oPurchaseSnMeta["ForbidStatus"] = "A";              //作废状态
                                    oPurchaseSnMeta["F_PMAF_PurchaseStatus"] = "A";
                                    oPurchaseSnMeta["F_PMAF_PurQty"] = purQty;          //采购数量
                                    oPurchaseSnMeta["F_PMAF_CurrentQty"] = purQty;      //当前数量
                                    oPurchaseSnMeta["F_PMAF_ContractMonth"] = contractMonth;
                                    oPurchaseSnMeta["F_PMAF_ContractMonth_Id"] = contractMonthId;
                                    oPurchaseSnMeta["F_PMAF_ContractType"] = contractType;
                                    oPurchaseSnMeta["F_PMAF_PurPrice"] = purPrice;
                                    oPurchaseSnMeta["F_PMAF_PurOrg"] = purOrg;
                                    oPurchaseSnMeta["F_PMAF_PurOrg_Id"] = purOrgId;
                                    oPurchaseSnMeta["F_PMAF_Rebate"] = rebate;
                                    list.Add(oPurchaseSnMeta);
                                }
                            }
                            if(oldEntries.Count> oldFlagEntries.Count)
                            {
                                foreach(DynamicObject oldEntry in oldEntries)
                                {
                                    int count = 0;
                                    int oldEntryId = Convert.ToInt32(oldEntry["Id"]);
                                    decimal oldQty = Convert.ToDecimal(oldEntry["Qty"]);
                                    foreach (DynamicObject oldFlagEntry in oldFlagEntries)
                                    {
                                        int oldFlagEntryId = Convert.ToInt32(oldFlagEntry["Id"]);
                                        if (oldEntryId == oldFlagEntryId)
                                        {
                                            count++;
                                        }
                                    }
                                    if (count == 0)
                                    {
                                        int oldPurchaseId = Convert.ToInt32(oldEntry["F_PMAF_PurchaseSnId_Id"]);
                                        DynamicObject[] oldPurchases = GetPurchaseSn(oldPurchaseId);
                                        oldPurchases[0]["F_PMAF_PurQty"] = Convert.ToDecimal(oldPurchases[0]["F_PMAF_PurQty"]) - oldQty;
                                        oldPurchases[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(oldPurchases[0]["F_PMAF_CurrentQty"]) - oldQty;
                                        if(Convert.ToDecimal(oldPurchases[0]["F_PMAF_PurQty"]) - oldQty == 0)
                                        {
                                            oldPurchases[0]["F_PMAF_PurchaseStatus"] = "B";
                                        }
                                        BusinessDataServiceHelper.Save(Context, oldPurchases);
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (DynamicObject row in entry)
                            {
                                int currentEntryId = Convert.ToInt32(row["Id"]);
                                DynamicObject oPurchaseSnMeta = new DynamicObject(purchaseSnMeta.BusinessInfo.GetDynamicObjectType());
                                var material = (DynamicObject)row["MaterialId"];    //物料
                                var materialId = Convert.ToInt32(material["Id"]);   //物料Id
                                var contractMonth = (DynamicObject)row["F_PMAF_ContractMonth"];    //合约月
                                string contractMonthId = string.Empty;
                                if (contractMonth != null)
                                {
                                    contractMonthId = contractMonth["Id"].ToString();
                                }
                                var purchaseSn = row["F_PMAF_PurchaseSN"];          //流水号
                                var purchaseSnId = row["F_PMAF_PurchaseSnId_Id"];
                                var purQty = Convert.ToDecimal(row["Qty"]);
                                decimal purPrice = Convert.ToDecimal(row["TaxPrice"]);
                                int contractType = Convert.ToInt32(row["F_PMAF_ContractType"]);
                                oPurchaseSnMeta["Number"] = purchaseSn;
                                oPurchaseSnMeta["F_PMAF_POOderNo"] = purOrderNo;
                                oPurchaseSnMeta["F_PMAF_SupplierID_Id"]= supplierId;
                                oPurchaseSnMeta["F_PMAF_SupplierID"] = supplier;
                                oPurchaseSnMeta["F_PMAF_EmpID_Id"] = empId;
                                oPurchaseSnMeta["F_PMAF_EmpID"] = emp;
                                oPurchaseSnMeta["F_PMAF_MaterialID_Id"] = materialId;
                                oPurchaseSnMeta["F_PMAF_MaterialID"] = material;
                                oPurchaseSnMeta["F_PMAF_CreateDate_tzk"] = createDate;
                                oPurchaseSnMeta["F_PMAF_ModifyDate_ca9"] = createDate;
                                oPurchaseSnMeta["DocumentStatus"] = "C";            //单据状态
                                oPurchaseSnMeta["ForbidStatus"] = "A";              //作废状态
                                oPurchaseSnMeta["F_PMAF_PurchaseStatus"] = "A";
                                oPurchaseSnMeta["F_PMAF_PurQty"] = purQty;          //采购数量
                                oPurchaseSnMeta["F_PMAF_CurrentQty"] = purQty;      //当前数量
                                oPurchaseSnMeta["F_PMAF_ContractMonth"] = contractMonth;
                                oPurchaseSnMeta["F_PMAF_ContractMonth_Id"] = contractMonthId;
                                oPurchaseSnMeta["F_PMAF_ContractType"] = contractType;
                                oPurchaseSnMeta["F_PMAF_PurPrice"] = purPrice;
                                oPurchaseSnMeta["F_PMAF_PurOrg"] = purOrg;
                                oPurchaseSnMeta["F_PMAF_PurOrg_Id"] = purOrgId;
                                oPurchaseSnMeta["F_PMAF_Rebate"] = rebate;
                                list.Add(oPurchaseSnMeta);
                            }
                        }
                        DynamicObject[] oPurchaseSnMetas = list.ToArray();
                        if (oPurchaseSnMetas.Length > 0)
                        {
                            ISaveService saveService = ServiceFactory.GetService<ISaveService>(Context);
                            IOperationResult saveResult = saveService.Save(Context, purchaseSnMeta.BusinessInfo, oPurchaseSnMetas, OperateOption.Create());
                            if (saveResult.IsSuccess)
                            {
                                List<DynamicObject> result = (List<DynamicObject>)saveResult.SuccessDataEnity;
                                foreach(DynamicObject row in entry)
                                {
                                    foreach (DynamicObject obj in result)
                                    {
                                        //取得流水号Id
                                        var id = obj["Id"];
                                        //订单行采购流水号
                                        string rowPurchaseSn = row["F_PMAF_PurchaseSN"].GetString();
                                        //返回结果采购流水号
                                        string purchaseSn = obj["Number"].GetString();
                                        if (rowPurchaseSn == purchaseSn)
                                        {
                                            //对单据体流水号字段赋值
                                            row["F_PMAF_PurchaseSnId_Id"] = id;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 查询流水号
        /// </summary>
        /// <param name="purchaseSnId"></param>
        /// <returns></returns>
        private DynamicObject[] GetPurchaseSn(int purchaseSnId)
        {
            //流水号过滤条件
            OQLFilter purchaseSnFilter = new OQLFilter
            {
                new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseSnId) }
            };
            //查询流水号
            DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, purchaseSnFilter);
            return purchaseSns;
        }
    }
}
